//
//  TravelViewController.m
//  ShareNavigation
//
//  Created by 水木 傅 on 12-5-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "TravelViewController.h"
#import "ASIFormDataRequest.h"
#import "SingletonUser.h"
#import "TravelBMKPointAnnotation.h"
#import "TravelTableViewController.h"

@implementation TravelViewController
@synthesize baiduMapView;
@synthesize returnXMLString;
@synthesize tempSignTravel;
@synthesize valueArray;
@synthesize switchString;
//---  解析xml  ---
-(void) analysisXML:(NSString *) XMLstring
{
    
    NSMutableString *xmlStr = [NSMutableString stringWithString:XMLstring];
   // NSLog(@"%d",[xmlStr length]);
   // NSLog(@"%d",[XMLstring length]);
   // NSLog(@"%d",XMLstring lengthOfBytesUsingEncoding:<#(NSStringEncoding)#>)
   // NSLog(@"%d",[xmlStr UTF8String]);
    NSData *data = [NSData dataWithBytes:[xmlStr UTF8String] length:[xmlStr lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    
    //---  设置xml数据  ---
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    [parser setDelegate: self];
    [parser parse];
}

//---  遍历xml节点  ---
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"name.:  %@",elementName);
    switchString = elementName;
}

//---  当xml有值，则调用函数  ---
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"value:   %@",string);
    //---  对每个值进行分析  ---
    if ([switchString isEqualToString:@"UUID"]) 
    {
        tempSignTravel.UUID = string;
    }
    else if([switchString isEqualToString:@"UserID"])
    {
        tempSignTravel.UserID = string;
    }
    else if([switchString isEqualToString:@"Location"])
    {
        tempSignTravel.Location = string;
    }
    else if([switchString isEqualToString:@"Time"])
    {
        tempSignTravel.Time = string;
    }
    else if([switchString isEqualToString:@"TravelSignature"])
    {
        tempSignTravel.TravelSignature = string;
    }
    else if([switchString isEqualToString:@"Longitude"])
    {
        tempSignTravel.Longitude = string;
    }
    else if([switchString isEqualToString:@"Latitude"])
    {
        tempSignTravel.Latitude = string;
    }
    else if([switchString isEqualToString:@"HasImage"])
    {
        //---  判断是否有图片  ---
        if([string isEqualToString:@"TRUE"])
        {
            NSLog(@"TRUE has image");
            tempSignTravel.hasImage = TRUE;
        }
        else
        {
            tempSignTravel.hasImage = FALSE;
        }
    }
        
}

//---  遇到结束标记，调用该函数  ---
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"结束标记：   %@",elementName);
    if([elementName isEqualToString:@"OneTravel"])
    {
        NSLog(@"------%@",elementName);
        NSLog(@"----%@",tempSignTravel.UUID);
        SignTravel *temp = [SignTravel alloc];
        [temp SetValueFromeObject:tempSignTravel];
        NSLog(@"%@",temp.Time);
        [valueArray addObject:temp];
        for(SignTravel* temp in valueArray)
       {
           NSLog(@"-+-+-+--0=-0=-0=0-=-0=0=-0=       %@",temp.Time);
       }
    }

    //---  xml解析完毕  ---
    if([elementName isEqualToString:@"body"])
    {
        NSLog(@"结束标记：   %@",elementName);
        NSLog(@"%d",[valueArray count]);
        int j = 0;
        CLLocationCoordinate2D startPoint;
        for(int i = 0 ; i < [valueArray count]  ;i++)
        {
            SignTravel* temp  = [valueArray objectAtIndex:i];
            //添加一个动态点
            //---   坐标  ---
            CLLocationCoordinate2D coors ;
            coors.longitude  = [temp.Longitude floatValue];
            coors.latitude = [temp.Latitude floatValue];
            //---  动态点  ---
            TravelBMKPointAnnotation *annotation = [[TravelBMKPointAnnotation alloc] init];
            annotation.UUID = temp.UUID;
            annotation.coordinate = coors;
            annotation.title = temp.TravelSignature;
            NSString* subTitle = [NSString stringWithFormat:@"签到时间: %@",temp.Time];
            annotation.subtitle = subTitle;
            [baiduMapView addAnnotation:annotation];
            if(i == 0)
            {
                BMKCoordinateRegion region;
                region.center = coors;
                baiduMapView.region = region;
            }
            //进行画线的选择
            if(j == 0)
            {
                startPoint.longitude = coors.longitude;
                startPoint.latitude = coors.latitude;
                j++;
            }
            else
            {
                [self drawLine:startPoint destinationPoint:coors];
                startPoint.longitude = coors.longitude;
                startPoint.latitude = coors.latitude;
            }
                        
        }
       /*
        // 添加折线覆盖物
        CLLocationCoordinate2D coors[2] = {0};
        coors[0].latitude = 39.315;
        coors[0].longitude = 116.304;
        coors[1].latitude = 39.515;
        coors[1].longitude = 116.504;
        BMKPolyline* polyline = [BMKPolyline polylineWithCoordinates:coors count:2];
        [mapView addOverlay:polyline];
        */

    }
}

//---  在地图上画线函数  ---
-(void) drawLine :(CLLocationCoordinate2D)startPoint destinationPoint:(CLLocationCoordinate2D) destination
{
    CLLocationCoordinate2D coors[2] = {0};
    coors[0].latitude = startPoint.latitude;
    coors[0].longitude = startPoint.longitude;
    coors[1].latitude = destination.latitude;
    coors[1].longitude = destination.longitude;
    BMKPolyline* polyline = [BMKPolyline polylineWithCoordinates:coors count:2];
    [baiduMapView addOverlay:polyline];
}

//---  异步回调的函数  ---

-(void) requestRegisterFinished :(ASIHTTPRequest *)request;
{
    NSString *response = request.responseString;
    NSLog(@"%@",response);
    if([response isEqualToString:@"FALSE"])
    {
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@"警告"
                 message:@"连接服务器错误"
                 delegate:self
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:@"重新查看行程",nil];
        [alert show];

    }
    else
    {
        returnXMLString = response;
        [self analysisXML:returnXMLString];
    }
}
-(void) requestRegisterFailed :(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error localizedFailureReason]);
}



//---  获取数据  ---
-(void) getData:(NSString *) UserId
{
    NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/Travel.php"];
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setPostValue:UserId forKey:@"UserID"];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestRegisterFinished:)];
    [request setDidFailSelector:@selector(requestRegisterFailed:)];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    //---  发送请求信息  ----
    [request startAsynchronous];
}

-(void) viewDidLoad
{
    [super viewDidLoad];
    tempSignTravel = [[SignTravel alloc]init];
    valueArray = [[NSMutableArray alloc]initWithObjects: nil];
    baiduMapView.delegate = self;
    if(![[SingletonUser shareManager].UserID isEqualToString:@""])
    {
        NSLog(@"%@",[SingletonUser shareManager].UserID );
        [self getData:[SingletonUser shareManager].UserID];
    }
}

- (void)viewDidUnload {
    [self setSwitchString:nil];
    [self setValueArray:nil];
    [self setTempSignTravel:nil];
    [self setReturnXMLString:nil];
    [self setBaiduMapView:nil];
    [super viewDidUnload];
}


#pragma  ---  百度地图委托  ---

//---  开始定位  ---
-(void)mapViewWillStartLocatingUser:(BMKMapView *)mapView
{
    NSLog(@"开始定位");
}

//---  更新坐标  ---
-(void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation
{
}

//---  定位失败  ---
-(void)mapView:(BMKMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
}

//定位停止

-(void)mapViewDidStopLocatingUser:(BMKMapView *)mapView
{    
    NSLog(@"定位停止");  
}

// ---   进行画线的控制函数  ---
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay{
	if ([overlay isKindOfClass:[BMKPolyline class]]){
		BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay] ;
		polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:1];
		polylineView.lineWidth = 3.0;
		return polylineView;
	}
	return nil;
}



#pragma ---  实现弹出窗口的delegate中的方法  ----

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        if(![[SingletonUser shareManager].UserID isEqualToString:@""])
            [self getData:[SingletonUser shareManager].UserID];
    }
}
#pragma  ---  切换到列表模式时候，传递数据  ---
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"show table view"])
    {
        TravelViewController *controller = (TravelViewController *)segue.destinationViewController;
        controller.valueArray = [self valueArray];
    }
}



@end
